<?php
use \Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use \AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use api\app\model\CodeModel;
//签发token
function createToken($userId,$mobile)
{
    $data = [
        //签发人
        'iss' => request()->domain(),
        //签发时间
        'iat' => time(),
        //自定义数据
        'data' =>[
            'user_id' => $userId,
            'mobile' => $mobile
        ]
    ];
    //自定义key
    $key = config('app.jwt_key');
    // halt($key);
    $token = \Firebase\JWT\JWT::encode($data,$key,'HS256');
    return $token;
}
//检查验证码是否正确
function checkCode($mobile,$code)
{
    $data = CodeModel::where('mobile',$mobile)->find();
    if (!$data){
        return false; // error('请发送验证码');
    }
    if ($code != $data['code'] ){
        return false; // error('验证码不正确');
    }
    if (time() - $data['create_time'] > 1200000000){
        CodeModel::where('mobile',$mobile)->delete();
        return false; //error('验证码超时，请重新发送');
    }else{
        CodeModel::where('mobile',$mobile)->delete();
        return true;
    }

}
//发送验证码
function SendCode($mobile)
{
    $code = mt_rand(1111, 9999);
    $config = new Config([
        // 从阿里云获取
        'accessKeyId' => config('app.code.accessKeyId'),
        'accessKeySecret' => config('app.code.accessKeySecret'),
    ]);

    $config->endpoint = "dysmsapi.aliyuncs.com";
    $client = new Dysmsapi($config);

    // 运行时参数超时设置，仅对使用了该运行时参数实例的请求有效
    $runtimeOptions = new RuntimeOptions();
    // true 忽略证书校验
    $runtimeOptions->ignoreSSL = true;

    $sendSmsRequest = new SendSmsRequest();
    // 手机号
    $sendSmsRequest->phoneNumbers = $mobile;
    // 签名名称
    $sendSmsRequest->signName = config('app.code.signName');
    // 模板CODE
    $sendSmsRequest->templateCode =  config('app.code.sms');
    // 生成随机数作为验证码
    $sendSmsRequest->templateParam = json_encode(['code' => $code]);
    try {
        $response = $client->sendSmsWithOptions($sendSmsRequest, $runtimeOptions);
    } catch (\Exception $exception) {
        halt($exception->getMessage());
    }
    $Smscode = new CodeModel();
    $Smscode->mobile = $mobile;
    $Smscode->code = $code;
    $Smscode->create_time = time();
    $Smscode->save();
    if ($response->body->code == 'OK') {
        return json([
            'code' => 1,
            'msg' => '短信发送成功',
            'data' => null
        ]);
    }else{
        return json([
            'code' => 0,
            'msg' => '短信发送失败',
            'data' => null
        ]);
    }
}
